<?php

namespace app\model;

use app\Log;
use GuzzleHttp\Client;
use think\Model;
use think\model\relation\HasOne;

class SupplierStation extends Model
{
    public function supplier_station_ids(): array
    {
        $sid = request()->param('supplier');
        return $this->where('supplier_id', $sid)->whereIn('state', [1, 2])->column('station_id');
    }

    public function station(): HasOne
    {
        return $this->hasOne(Stations::class, "id", "station_id");
    }

    public function oil()
    {
        return $this->hasMany(StationOil::class, "station_id", "station_id");
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->with(['station','oil'])->when(!empty($param['supplier']), function ($query) use ($param) {
            $query->where('supplier_id', $param['supplier']);
        })->when(!empty($param['name']), function ($query) use ($param) {
            $ids = Stations::where('name', 'like', "%{$param['name']}%")->column('id');
            $query->whereIn('station_id', $ids);
        })->order("create_time desc")->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        return pageData($data);
    }

    public function saveStation()
    {
        $param = request()->post();
        $type = request()->param('type');
        switch ((int)$param['tag']) {
            case 2:
                $ids = $this->whereIn("station_id", $param['station'])->where("supplier_id", $param['supplier'])->column("id");
                if (empty($ids)) throw new \Exception('数据不存在');
                $update = ['discount' => $param['discount']];
//                if (!empty($param['start_time'])) {
//                    $update['start_time'] = $param['start_time'];
//                    $update['type'] = 2;
//                }
                if (!empty($param['end_time'])) {
                    $update['end_time'] = $param['end_time'];
                }
                $this->whereIn("id", $ids)->update($update);
                break;
            case 3:
                $ids = $this->whereIn("station_id", $param['station'])->where("supplier_id", $param['supplier'])->column("id");
                if (empty($ids)) throw new \Exception('数据不存在');
                $this->whereIn("id", $ids)->delete();
                break;
            default:
                $its = array_map(function ($items) use ($param) {
                    return [
                        "supplier_id" => $param['supplier'],
                        "station_id" => $items,
                        "discount" => $param['discount'],
                        "start_time" => empty($param['start_time']) ? date("Y-m-d H:i:s") : $param['start_time'],
                        "end_time" => $param['end_time'] ?? null,
                        "state" => 2
                    ];
                }, $param['station']);
                $this->saveAll($its);
                break;
        }

        if ($type == "push") {
            //向渠道推送数据
            $notify = app(Supplier::class)->where("id", $param['supplier'])->find();
            if (!empty($notify) && !empty($data['station_notify_url'])) {
                $time = time();
                $data = ['gasId' => $param['station'], 'time' => $time, 'sign', 'sign' => md5($notify['out_key'] . $time . $notify['token']), 'type' => $param['tag']];
                $client = new Client([
                    "base_uri" => $notify['station_notify_url'],
                    "verify" => false,
                    "headers" => ['Content-Type' => 'application/json; charset=utf-8']
                ]);
                $log = new Log("supplier_station_push");
                try {
                    $res = $client->post("", [
                        'json' => $data
                    ]);
                    if ($res->getStatusCode() != 200) throw new \Exception("请求失败");
                    $content = $res->getBody()->getContents();
                    $log->write(["res" => $content, 'param' => $data]);
                } catch (\Exception $e) {
                    $log->write(["error" => $e->getMessage(), 'param' => $data], "error");
                }
            }
        }

        return $param['station'];
    }
}
